package com.example.smartgreenhouse.WebSocketServer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ThresholdWebSocketServer {
    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    public ThresholdWebSocketServer(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    public void sendThresholdUpdate(String type, int minValue, int maxValue) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("thresholdType", type);
            message.put("minValue", minValue);
            message.put("maxValue", maxValue);
            message.put("updateTime", System.currentTimeMillis());
            
            messagingTemplate.convertAndSend("/topic/threshold_updates", message);
            log.info("已推送阈值更新到WebSocket: {}={}-{}", type, minValue, maxValue);
        } catch (Exception e) {
            log.error("阈值更新WebSocket推送失败 | 类型: {} | 错误: {}", type, e.getMessage());
        }
    }
}